package com.ad.aidai.fragments.forget_password;

import android.content.Context;
import android.content.SharedPreferences;

import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResultWithData;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import cn.smssdk.SMSSDK;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.content.Context.MODE_PRIVATE;

/**
 * ForgetPasswordPresenter
 * <p>
 * Created by Yusxon on 16/12/18.
 */

public class ForgetPasswordPresenter implements ForgetPasswordContract.Presenter {

    private Context mContext;
    private ForgetPasswordContract.View mView;
    private CompositeSubscription mSubscriptions;
    private Gson gson;
    private SharedPreferences aidaiSP;

    public ForgetPasswordPresenter(Context context, ForgetPasswordContract.View view) {
        this.mContext = context;
        this.mView = view;
        gson = new Gson();
        mView.setPresenter(this);
        aidaiSP = mContext.getSharedPreferences("AIDAI", MODE_PRIVATE);
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public void loadPhone() {
        if (mView != null) {
            mView.setPhoneNumber(aidaiSP.getString("USER_PHONE", ""));
        }
    }

    @Override
    public void sendVerificationCode(final String phoneNumber) {
        if (CheckUtil.checkStrNull(phoneNumber)) {
            if (mView != null) {
                mView.toast("请输入手机号");
            }
        } else if (!CheckUtil.checkPhone(phoneNumber)) {
            if (mView != null) {
                mView.toast("手机号格式不正确");
            }
        } else {
            if (mView != null) {
                mView.setVCButtonClickable(false);
            }
            Subscription subscription = Observable
                    .create(new Observable.OnSubscribe<Object>() {
                        @Override
                        public void call(Subscriber<? super Object> subscriber) {
                            SMSSDK.getVerificationCode("86", phoneNumber);
                            for (int i = 59; i >= 0; --i) {
                                if (mView != null) {
                                    try {
                                        Thread.sleep(1000);
                                        Logger.t(this.getClass().getSimpleName()).i("i:" + i);
                                        subscriber.onNext(i);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Object>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            Logger.t(this.getClass().getSimpleName()).e(e.getMessage());
                            if (mView != null) {
                                mView.toast("获取验证码失败");
                                mView.setVCButtonClickable(true);
                            }
                        }

                        @Override
                        public void onNext(Object o) {
                            if (o instanceof Integer) {
                                if (mView != null) {
                                    mView.showVerficationCodeCountDown("重发(" + o + "s)");
                                    if ((int) o == 0) {
                                        mView.setVCButtonClickable(true);
                                    }
                                }
                            }
                        }
                    });
            mSubscriptions.add(subscription);
        }
    }

    @Override
    public void verifyPhone(String phoneNumber, String verficationCode) {
        if (CheckUtil.checkStrNull(phoneNumber) || CheckUtil.checkStrNull
                (verficationCode)) {
            if (mView != null) {
                mView.toast("手机号和验证码不能为空");
            }
        } else if (!CheckUtil.checkPhone(phoneNumber)) {
            if (mView != null) {
                mView.toast("手机号格式不正确");
            }
        } else {
            //显示加载对话框
            if (mView != null) {
                mView.showLoading();
                NetWork.getAccountOperationApi()
                        .forgetPassword(phoneNumber, verficationCode)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<NetResultWithData>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.t("ForgetPasswordPresenter").e(e.getMessage());
                                //关闭加载对话框
                                mView.closeLoading(false);
                            }

                            @Override
                            public void onNext(NetResultWithData netResultWithData) {
                                Logger.t("ForgetPasswordPresenter").i(netResultWithData.toString());
                                if (netResultWithData.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                                    mView.closeLoading(false);
                                } else {
                                    String token = (String)netResultWithData.getData();
                                    mView.closeLoading(true);
                                    mView.verifySuccess(token);
                                }
                            }
                        });
            }
        }
    }

    @Override
    public void savePhone(String phone) {
        aidaiSP.edit()
                .putString("USER_PHONE", phone)
                .apply();
    }

}
